package com.basic.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.basic.common.exception.RRException;
import com.basic.common.utils.*;
import com.basic.common.validator.ValidatorUtils;
import com.basic.modules.sys.entity.SysEmailConfigEntity;
import com.basic.modules.sys.model.SysEmailModel;
import com.basic.modules.sys.service.SysEmailConfigService;
import com.basic.modules.ykf.entity.YkfAccountInputRecordEntity;
import com.sun.mail.imap.IMAPMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * 系统用户
 *
 * @author maoheng
 * @email 15738859597@163.com
 * @date 2024-11-22 15:06:22
 */
@Slf4j
@RestController
@RequestMapping("sys/email")
public class SysEmailController {

    @Autowired
    private SysEmailConfigService sysEmailConfigService;

    /**
     * 列表-分页
     */
    @PostMapping("/emailMsgPage")
    public R list(@RequestBody ParamsModel<SysEmailModel> params) throws MessagingException, IOException {
        List<SysEmailModel> emailModelList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(params)
                && ObjectUtil.isNotEmpty(params.getCondition())
                && ObjectUtil.isNotEmpty(params.getCondition().getEmailConfigId())) {
            SysEmailConfigEntity record = sysEmailConfigService.getById(params.getCondition().getEmailConfigId());
            Properties props = new Properties();
            props.setProperty("mail.store.protocol", "imap");
            String host = "";
            if (StrUtil.equals(record.getEmailType(), "1")) {
                host = "imap.qiye.aliyun.com";
            } else if (StrUtil.equals(record.getEmailType(), "2")) {
                host = "imap.qq.com";
            } else {
                return R.ok(new PageUtils());
            }
            props.setProperty("mail.imap.host", host);
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.ssl.enable", "true");

            Session session = Session.getInstance(props);
            Store store = session.getStore("imap");
            store.connect(record.getEmailUrl(), record.getPassword());

            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            Message[] messages = inbox.getMessages();
            if (ObjectUtil.isNotEmpty(messages)) {
                List<Message> list = Arrays.asList(messages);
                //结果分页
                IPage<SysEmailModel> page = new Query<SysEmailModel>().getPage(BeanUtil.beanToMap(params.getPage()));
                int totalcount = messages.length;
                Long size = params.getPage().getSize();
                Long current = params.getPage().getIndex();
                page.setTotal(totalcount);
                long pagecount = 0;
                long m = totalcount % size;
                if (m > 0) {
                    pagecount = totalcount / size + 1;
                } else {
                    pagecount = totalcount / size;
                }
                page.setPages(pagecount);
                if (m == 0) {
                    list = list.subList((int) ((current - 1) * size), (int) (size * (current)));
                } else {
                    if (current == pagecount) {
                        list = list.subList((int) ((current - 1) * size), (int) totalcount);
                    } else {
                        list = list.subList((int) ((current - 1) * size), (int) (size * (current)));
                    }
                }
                for (Message message : list) {
                    try {
                        String subject = message.getSubject();
                        Object content = message.getContent();
                        Date receivedDate = message.getReceivedDate();
                        SysEmailModel sm = new SysEmailModel();
                        sm.setSubject(subject);
                        sm.setContent(StrUtil.toString(content));
                        sm.setDate(receivedDate);
                        emailModelList.add(sm);
                    } catch (Exception e) {
                        log.info(e.getMessage());
                    }
                }
                page.setRecords(emailModelList);
                page.setSize(size);
                page.setCurrent(current);
                return R.ok(new PageUtils(page));
            }


            inbox.close(false);
            store.close();
        }

        return R.ok(new PageUtils());
    }

    /**
     * 列表-分页
     */
    @PostMapping("/getEmailStatus")
    public R getEmailStatus() throws MessagingException {
        int readCount = 0;
        int unReadCount = 0;
        QueryWrapper<SysEmailConfigEntity> queryWrapper = new QueryWrapper<>();
//        Long userId = CommonUtils.getUserId();
//        queryWrapper.lambda().eq(SysEmailConfigEntity::getCreateUserId, userId);
        List<SysEmailConfigEntity> list1 = sysEmailConfigService.list(queryWrapper);
        if (ObjectUtil.isNotEmpty(list1)) {
            for (SysEmailConfigEntity record : list1) {
                Properties props = new Properties();
                props.setProperty("mail.store.protocol", "imap");
                props.setProperty("mail.imap.partialfetch", "true"); // 设置为true以启用部分获取
                String host = "";
                if (StrUtil.equals(record.getEmailType(), "1")) {
                    host = "imap.qiye.aliyun.com";
                    props.setProperty("mail.imap.host", host);
                    props.setProperty("mail.imap.port", "993");
                    props.setProperty("mail.imap.ssl.enable", "true");

                    Session session = Session.getInstance(props);
                    Store store = session.getStore("imap");
                    try {
                        store.connect(record.getEmailUrl(), record.getPassword());
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    Folder inbox = store.getFolder("INBOX");
                    inbox.open(Folder.READ_ONLY);
//
                    Date threeMonthsAgo = new Date();
                    threeMonthsAgo.setTime(threeMonthsAgo.getTime() - (3L * 30L * 24L * 60L * 60L * 1000L)); // 三个月前的日期
                    Message[] messages = inbox.getMessages();
                    if (ObjectUtil.isNotEmpty(messages)) {
                        for (Message message : messages) {
                            try {
                                IMAPMessage imapMessage = (IMAPMessage) message;
                                Date receivedDate = imapMessage.getReceivedDate();
                                if (receivedDate != null && receivedDate.after(threeMonthsAgo)) {
                                    if (message.isSet(Flags.Flag.SEEN)) {
                                        //已读
                                        readCount ++;
                                    } else {
                                        //未读
                                        unReadCount ++;
                                    }
                                }
                            } catch (Exception e) {
                                log.info(e.getMessage());
                            }
                        }
                    }
                    inbox.close(false);
                    store.close();
                } else if (StrUtil.equals(record.getEmailType(), "2")) {
                    host = "imap.qq.com";
                    props.setProperty("mail.imap.host", host);
                    props.setProperty("mail.imap.port", "993");
                    props.setProperty("mail.imap.ssl.enable", "true");

                    Session session = Session.getInstance(props);
                    Store store = session.getStore("imap");
                    try {
                        store.connect(record.getEmailUrl(), record.getPassword());
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                    Folder inbox = store.getFolder("INBOX");
                    inbox.open(Folder.READ_ONLY);

                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.MONTH, -3);
                    ReceivedDateTerm sentDateTerm = new ReceivedDateTerm(ComparisonTerm.GT, new Date(calendar.getTimeInMillis()));
                    Message[] messages = inbox.search(sentDateTerm);
                    if (ObjectUtil.isNotEmpty(messages)) {
                        for (Message message : messages) {
                            try {
                                if (message.isSet(Flags.Flag.SEEN)) {
                                    //已读
                                    readCount ++;
                                } else {
                                    //未读
                                    unReadCount ++;
                                }
                            } catch (Exception e) {
                                log.info(e.getMessage());
                            }
                        }
                    }
                    inbox.close(false);
                    store.close();
                }
            }
        }
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("readStatus", "1");
        map1.put("count", readCount);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("readStatus", "2");
        map2.put("count", unReadCount);
        list.add(map1);
        list.add(map2);
        return R.ok(list);
    }


    /**
     * 列表-分页
     */
    @PostMapping("/emailPage")
    public R emailPage(@RequestBody ParamsModel<SysEmailModel> params) throws MessagingException {
        List<SysEmailModel> emailModelList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(params) && ObjectUtil.isNotEmpty(params.getCondition()) && ObjectUtil.isNotEmpty(params.getCondition().getReadStatus())) {
            QueryWrapper<SysEmailConfigEntity> queryWrapper = new QueryWrapper<>();
//            Long userId = CommonUtils.getUserId();
//            queryWrapper.lambda().eq(SysEmailConfigEntity::getCreateUserId, userId);
            List<SysEmailConfigEntity> list1 = sysEmailConfigService.list(queryWrapper);
            if (ObjectUtil.isNotEmpty(list1)) {
                for (SysEmailConfigEntity record : list1) {
                    Properties props = new Properties();
                    props.setProperty("mail.store.protocol", "imap");
                    props.setProperty("mail.imap.partialfetch", "true"); // 设置为true以启用部分获取
                    String host = "";
                    if (StrUtil.equals(record.getEmailType(), "1")) {
                        host = "imap.qiye.aliyun.com";
                        props.setProperty("mail.imap.host", host);
                        props.setProperty("mail.imap.port", "993");
                        props.setProperty("mail.imap.ssl.enable", "true");
                        Session session = Session.getInstance(props);
                        Store store = session.getStore("imap");
                        try {
                            store.connect(record.getEmailUrl(), record.getPassword());
                        } catch (Exception e) {
                            //链接失败，跳过进入下一个
                            e.printStackTrace();
                            continue;
                        }
                        Folder inbox = store.getFolder("INBOX");
                        inbox.open(Folder.READ_ONLY);
                        Message[] messages = inbox.getMessages();
                        Date threeMonthsAgo = new Date();
                        threeMonthsAgo.setTime(threeMonthsAgo.getTime() - (3L * 30L * 24L * 60L * 60L * 1000L)); // 三个月前的日期

//                        Calendar calendar = Calendar.getInstance();
//                        calendar.add(Calendar.MONTH, -3);
//                        SentDateTerm sentDateTerm = new SentDateTerm(ComparisonTerm.GT, new Date(calendar.getTimeInMillis()));
//                        Message[] messages = inbox.search(sentDateTerm);
                        if (ObjectUtil.isNotEmpty(messages)) {
                            for (Message message : messages) {
                                try {
                                    IMAPMessage imapMessage = (IMAPMessage) message;
                                    String subject = imapMessage.getSubject();
                                    String messageID = imapMessage.getMessageID().replace("&", "&amp;")
                                            .replace("<", "&lt;")
                                            .replace(">", "&gt;")
                                            .replace("\"", "&quot;")
                                            .replace("'", "&apos;");
//                                Object content = message.getContent();
                                    Date receivedDate = imapMessage.getReceivedDate();
                                    if (receivedDate != null && receivedDate.after(threeMonthsAgo)) {

                                        if (message.isSet(Flags.Flag.SEEN)) {
                                            if (StrUtil.equals(params.getCondition().getReadStatus(), "1")) {
                                                SysEmailModel sm = new SysEmailModel();
                                                sm.setSubject(subject);
//                                    sm.setContent(StrUtil.toString(content));
                                                sm.setDate(receivedDate);
                                                sm.setEmailConfigId(record.getEmailConfigId());
                                                sm.setEmailType(record.getEmailType());
                                                sm.setEmailUrl(record.getEmailUrl());
                                                sm.setMessageId(messageID);
                                                sm.setReadStatus(params.getCondition().getReadStatus());
                                                emailModelList.add(sm);
                                            }
                                        } else {
                                            if (StrUtil.equals(params.getCondition().getReadStatus(), "2")) {
                                                SysEmailModel sm = new SysEmailModel();
                                                sm.setSubject(subject);
//                                    sm.setContent(StrUtil.toString(content));
                                                sm.setDate(receivedDate);
                                                sm.setEmailConfigId(record.getEmailConfigId());
                                                sm.setEmailType(record.getEmailType());
                                                sm.setEmailUrl(record.getEmailUrl());
                                                sm.setMessageId(messageID);
                                                sm.setReadStatus(params.getCondition().getReadStatus());
                                                emailModelList.add(sm);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.info(e.getMessage());
                                }
                            }
                        }
                        inbox.close(false);
                        store.close();
                    } else if (StrUtil.equals(record.getEmailType(), "2")) {
                        host = "imap.qq.com";
                        props.setProperty("mail.imap.host", host);
                        props.setProperty("mail.imap.port", "993");
                        props.setProperty("mail.imap.ssl.enable", "true");

                        Session session = Session.getInstance(props);
                        Store store = session.getStore("imap");
                        try {
                            store.connect(record.getEmailUrl(), record.getPassword());
                        } catch (Exception e) {
                            //链接失败，跳过进入下一个
                            e.printStackTrace();
                            continue;
                        }
                        Folder inbox = store.getFolder("INBOX");
                        inbox.open(Folder.READ_ONLY);
//                    int entCount = 50;
//                    if (inbox.getMessageCount() < 50) {
//                        entCount = inbox.getMessageCount();
//                    }
//                    Message[] messages = inbox.getMessages(1, entCount);
                        Calendar calendar = Calendar.getInstance();
                        calendar.add(Calendar.MONTH, -3);
                        ReceivedDateTerm sentDateTerm = new ReceivedDateTerm(ComparisonTerm.GT, new Date(calendar.getTimeInMillis()));
                        Message[] messages = inbox.search(sentDateTerm);
                        if (ObjectUtil.isNotEmpty(messages)) {
                            for (Message message : messages) {
                                try {
                                    IMAPMessage imapMessage = (IMAPMessage) message;
                                    String subject = imapMessage.getSubject();
//                                Object content = message.getContent();
                                    Date receivedDate = imapMessage.getReceivedDate();
                                    String messageID = imapMessage.getMessageID().replace("&", "&amp;")
                                            .replace("<", "&lt;")
                                            .replace(">", "&gt;")
                                            .replace("\"", "&quot;")
                                            .replace("'", "&apos;");
                                    if (message.isSet(Flags.Flag.SEEN)) {
                                        if (StrUtil.equals(params.getCondition().getReadStatus(), "1")) {
                                            SysEmailModel sm = new SysEmailModel();
                                            sm.setSubject(subject);
//                                    sm.setContent(StrUtil.toString(content));
                                            sm.setDate(receivedDate);
                                            sm.setEmailConfigId(record.getEmailConfigId());
                                            sm.setEmailType(record.getEmailType());
                                            sm.setEmailUrl(record.getEmailUrl());
                                            sm.setMessageId(messageID);
                                            sm.setReadStatus(params.getCondition().getReadStatus());
                                            emailModelList.add(sm);
                                        }
                                    } else {
                                        if (StrUtil.equals(params.getCondition().getReadStatus(), "2")) {
                                            SysEmailModel sm = new SysEmailModel();
                                            sm.setSubject(subject);
//                                    sm.setContent(StrUtil.toString(content));
                                            sm.setDate(receivedDate);
                                            sm.setEmailConfigId(record.getEmailConfigId());
                                            sm.setEmailType(record.getEmailType());
                                            sm.setEmailUrl(record.getEmailUrl());
                                            sm.setMessageId(messageID);
                                            sm.setReadStatus(params.getCondition().getReadStatus());
                                            emailModelList.add(sm);
                                        }
                                    }
                                } catch (Exception e) {
                                    log.info(e.getMessage());
                                }
                            }
                        }
                        inbox.close(false);
                        store.close();
                    } else {
                        return R.ok(new PageUtils());
                    }
                }
            } else {
                return R.ok(new PageUtils());
            }
            emailModelList.sort(Comparator.comparing(SysEmailModel::getDate).reversed());
            //结果分页
            IPage<SysEmailModel> page = new Query<SysEmailModel>().getPage(BeanUtil.beanToMap(params.getPage()));
            int totalcount = emailModelList.size();
            Long size = params.getPage().getSize();
            Long current = params.getPage().getIndex();
            page.setTotal(totalcount);
            long pagecount = 0;
            long m = totalcount % size;
            if (m > 0) {
                pagecount = totalcount / size + 1;
            } else {
                pagecount = totalcount / size;
            }
            page.setPages(pagecount);
            if (emailModelList.size() > 0) {
                if (m == 0) {
                    emailModelList = emailModelList.subList((int) ((current - 1) * size), (int) (size * (current)));
                } else {
                    if (current == pagecount) {
                        emailModelList = emailModelList.subList((int) ((current - 1) * size), (int) totalcount);
                    } else {
                        emailModelList = emailModelList.subList((int) ((current - 1) * size), (int) (size * (current)));
                    }
                }
            }
            page.setRecords(emailModelList);
            page.setSize(size);
            page.setCurrent(current);
            return R.ok(new PageUtils(page));
        }
        return R.ok(new PageUtils());
    }


    /**
     * 获取邮件详情
     */
    @PostMapping("/getEmailInfo")
    public R getEmailInfo(@RequestBody SysEmailModel emailModel) throws MessagingException {
        if (ObjectUtil.isNotEmpty(emailModel)
                && StrUtil.isNotBlank(emailModel.getReadStatus())
                && StrUtil.isNotBlank(emailModel.getMessageId())
                && ObjectUtil.isNotEmpty(emailModel.getEmailConfigId())) {
            SysEmailConfigEntity record = sysEmailConfigService.getById(emailModel.getEmailConfigId());
            if (ObjectUtil.isNotEmpty(record)) {
                Properties props = new Properties();
                props.setProperty("mail.store.protocol", "imap");
                props.setProperty("mail.imap.partialfetch", "true"); // 设置为true以启用部分获取
                String host = "";
                if (StrUtil.equals(record.getEmailType(), "1")) {
                    host = "imap.qiye.aliyun.com";
                    props.setProperty("mail.imap.host", host);
                    props.setProperty("mail.imap.port", "993");
                    props.setProperty("mail.imap.ssl.enable", "true");

                    Session session = Session.getInstance(props);
                    Store store = session.getStore("imap");
                    store.connect(record.getEmailUrl(), record.getPassword());

                    Folder inbox = store.getFolder("INBOX");
                    inbox.open(Folder.READ_ONLY);
//
                    Date threeMonthsAgo = new Date();
                    threeMonthsAgo.setTime(threeMonthsAgo.getTime() - (3L * 30L * 24L * 60L * 60L * 1000L)); // 三个月前的日期

                    Message[] messages = inbox.getMessages();
                    if (ObjectUtil.isNotEmpty(messages)) {
                        for (Message message : messages) {
                            try {
                                IMAPMessage imapMessage = (IMAPMessage) message;
                                String subject = imapMessage.getSubject();
                                String messageID = imapMessage.getMessageID().replace("&", "&amp;")
                                        .replace("<", "&lt;")
                                        .replace(">", "&gt;")
                                        .replace("\"", "&quot;")
                                        .replace("'", "&apos;");
                                Date receivedDate = imapMessage.getReceivedDate();
                                if (receivedDate != null && receivedDate.after(threeMonthsAgo) && StrUtil.equals(messageID, emailModel.getMessageId())) {
                                    if (!message.isSet(Flags.Flag.SEEN) && StrUtil.equals(emailModel.getReadStatus(), "2")) {
                                        message.setFlag(Flags.Flag.SEEN, true);
                                    }
                                    SysEmailModel sm = new SysEmailModel();
                                    sm.setSubject(subject);
                                    Object content = message.getContent();
                                    if (content instanceof String) {
                                        sm.setContent(StrUtil.toString(content));
                                    }
//                                    else if (content instanceof MimeMultipart) {
//                                        MimeMultipart multipart = (MimeMultipart) content;
//                                        for (int i = 0; i < multipart.getCount(); i++) {
//                                            BodyPart bodyPart = multipart.getBodyPart(i);
//                                            String disposition = bodyPart.getDisposition();
//
//                                            if (BodyPart.ATTACHMENT.equalsIgnoreCase(disposition)) {
//                                                // 这是一个附件
//                                                // 处理附件...
//                                                sm.setContent("");
//                                            } else if (BodyPart.INLINE.equalsIgnoreCase(disposition)) {
//                                                // 这是一个内联资源
//                                                // 处理内联资源...
//                                                sm.setContent("");
//                                            } else {
//                                                // 这是邮件的正文
//                                                String contentType = bodyPart.getContentType();
//                                                Object partContent = bodyPart.getContent();
//                                                // 处理正文内容...
//                                                sm.setContent(StrUtil.toString(partContent));
//                                            }
//                                        }
//                                    }
                                    else {
                                        sm.setContent("");
                                    }
                                    sm.setDate(receivedDate);
                                    sm.setEmailConfigId(record.getEmailConfigId());
                                    sm.setEmailType(record.getEmailType());
                                    sm.setEmailUrl(record.getEmailUrl());
                                    sm.setMessageId(messageID);
                                    return R.ok(sm);
                                }
                            } catch (Exception e) {
                                log.info(e.getMessage());
                            }
                        }
                    }
                    inbox.close(false);
                    store.close();
                } else if (StrUtil.equals(record.getEmailType(), "2")) {
                    host = "imap.qq.com";
                    props.setProperty("mail.imap.host", host);
                    props.setProperty("mail.imap.port", "993");
                    props.setProperty("mail.imap.ssl.enable", "true");

                    Session session = Session.getInstance(props);
                    Store store = session.getStore("imap");
                    store.connect(record.getEmailUrl(), record.getPassword());

                    Folder inbox = store.getFolder("INBOX");
                    inbox.open(Folder.READ_ONLY);
//                    int entCount = 50;
//                    if (inbox.getMessageCount() < 50) {
//                        entCount = inbox.getMessageCount();
//                    }
//                    Message[] messages = inbox.getMessages(1, entCount);
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.MONTH, -3);
                    ReceivedDateTerm sentDateTerm = new ReceivedDateTerm(ComparisonTerm.GT, new Date(calendar.getTimeInMillis()));
                    Message[] messages = inbox.search(sentDateTerm);
                    if (ObjectUtil.isNotEmpty(messages)) {
                        for (Message message : messages) {
                            try {
                                IMAPMessage imapMessage = (IMAPMessage) message;
                                String subject = imapMessage.getSubject();
//                                Object content = message.getContent();
                                Date receivedDate = imapMessage.getReceivedDate();
                                String messageID = imapMessage.getMessageID().replace("&", "&amp;")
                                        .replace("<", "&lt;")
                                        .replace(">", "&gt;")
                                        .replace("\"", "&quot;")
                                        .replace("'", "&apos;");
                                if (StrUtil.equals(messageID, emailModel.getMessageId())) {
                                    if (!message.isSet(Flags.Flag.SEEN) && StrUtil.equals(emailModel.getReadStatus(), "2")) {
                                        message.setFlag(Flags.Flag.SEEN, true);
                                    }
                                    SysEmailModel sm = new SysEmailModel();
                                    sm.setSubject(subject);
                                    Object content = message.getContent();
                                    if (content instanceof String) {
                                        sm.setContent(StrUtil.toString(content));
                                    } else {
                                        sm.setContent("");
                                    }
                                    sm.setDate(receivedDate);
                                    sm.setEmailConfigId(record.getEmailConfigId());
                                    sm.setEmailType(record.getEmailType());
                                    sm.setEmailUrl(record.getEmailUrl());
                                    sm.setMessageId(messageID);
                                    return R.ok(sm);
                                }
                            } catch (Exception e) {
                                log.info(e.getMessage());
                            }
                        }
                    }
                    inbox.close(false);
                    store.close();
                } else {
                    return R.ok(new SysEmailModel());
                }
            } else {
                return R.ok(new SysEmailModel());
            }
            return R.ok(new SysEmailModel());
        } else {
            throw new RRException("参数缺失");
        }
    }

}
